package com.heima.reggie.controller;

import com.heima.reggie.bean.ShoppingCart;
import com.heima.reggie.bean.User;
import com.heima.reggie.common.R;
import com.heima.reggie.service.ShoppingCartServcie;
import com.heima.reggie.utils.BaseContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.runtime.RewriteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Api(tags = "购物车管理")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartServcie shoppingCartServcie;

    @ApiOperation(value ="添加购物车")
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart,HttpSession session) {
        User user = (User) session.getAttribute("user");
        System.out.println("-------");
        System.out.println(shoppingCart);
        ShoppingCart add = shoppingCartServcie.add(shoppingCart,user.getId());
        if (add != null) {
            return R.success(add);
        } else {
            return R.error("添加失败！");
        }
    }

    @ApiOperation(value ="按用户id查询购物车")
    @GetMapping("/list")
    public R findByUid(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<ShoppingCart> list=shoppingCartServcie.findByUid(user.getId());
        if (list != null) {
            return R.success(list);
        } else {
            return R.error("查询失败！");
        }

    }

    @ApiOperation(value ="清空购物车")
    @DeleteMapping("/clean")
    public R clean(HttpSession session) {
        User user = (User) session.getAttribute("user");
        int i = shoppingCartServcie.clean(user.getId());
        if (i > 0) {
            return R.success("清空成功！");
        } else {
            return R.error("清空失败！");
        }
    }
}
